package com.ben.utils.net

/**
 * Created by LiuYang on 2017/3/28.
 */

import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import com.ben.utils.ext.tryCatch
import java.net.NetworkInterface
import java.net.SocketException
import java.util.ArrayList
import java.util.regex.Pattern

/**
 * @Author: bin.yang
 * @Maintainer: bin.yang
 * @Date: 2019/12/24
 * @Copyright: 2019  Inc. All rights reserved.
 * @description: 网络工具类
 */
object NetWorkUtils {

    /**
     *  wifi 6
     */
    private const val WIFI_STANDARD_11AX = 6

    /**
     *  是否有网
     */
    fun isNetworkAvailable(context: Context?): Boolean {
        context ?: return false
        val conManager = context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        return conManager?.activeNetworkInfo?.isAvailable == true
    }

    /**
     *  热点开关是否打开
     */
    fun isWifiApEnabled(context: Context): Boolean {
        tryCatch {
            val wifiManager: WifiManager? =
                context.applicationContext?.getSystemService(WIFI_SERVICE) as? WifiManager
            val method = wifiManager?.javaClass?.getMethod("isWifiApEnabled")
            method?.isAccessible = true
            return method?.invoke(wifiManager) as? Boolean ?: false
        }
        return false
    }

    /**
     *  当前wifi是否为WiFi6
     */
    @SuppressLint("MissingPermission")
    fun isWifi6(context: Context): Boolean {
        tryCatch {
            val wifiManager: WifiManager =
                context.applicationContext?.getSystemService(WIFI_SERVICE) as? WifiManager
                    ?: return false
            val wifiInfo = wifiManager.connectionInfo ?: return false
            val scanResult = wifiManager.scanResults?.find {
                it.BSSID == wifiInfo.bssid
            }
            val method = scanResult?.javaClass?.getMethod("getWifiStandard") ?: return false
            method.isAccessible = true
            val wifiStandard = method.invoke(scanResult) as? Int ?: return false

            method.isAccessible = false
            return WIFI_STANDARD_11AX == wifiStandard
        }
        return false
    }

    /**
     * 判断Wifi网络是否可用
     */
    fun isWifiConnected(context: Context): Boolean {
        return try {
            val connectManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            val wifiInfo = connectManager?.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            if (wifiInfo?.isAvailable == null) return false else wifiInfo.isAvailable
        } catch (t: Throwable) {
            t.printStackTrace()
            false
        }
    }

    /**
     * 获取网络连接类型
     */
    fun getNetworkTypeConnected(context: Context): Int {
        tryCatch {
            val connectManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            val netInfo = connectManager?.activeNetworkInfo
            return netInfo?.subtype ?: 0
        }
        return 0
    }

    /**
     * 获取内网IP地址
     */
    fun getLocalIp(): String? {
        val list = ArrayList<String>()
        try {
            val en = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf = en.nextElement()
                val enumIpAddr = intf.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress) {
                        list.add(inetAddress.hostAddress)
                    }
                }
            }
        } catch (ex: SocketException) {
            ex.printStackTrace()
        }

        if (list.size > 0) {
            for (ip in list) {
                if (matchIP(ip)) {
                    return ip
                }
            }
        }
        return null
    }

    private fun matchIP(ip: String): Boolean {
        val regex =
            "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\." + "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"
        val pattern = Pattern.compile(regex)
        val matcher = pattern.matcher(ip)
        return matcher.matches()
    }
}
